home *** CD-ROM | disk | FTP | other *** search
/ Introduction to 3D Game …ogramming with DirectX 12 / Introduction-to-3D-Game-Programming-with-DirectX-12.ISO / Code.Textures / Chapter 10 Blending / BlendDemo / BlendApp.cpp next >
Encoding:
C/C++ Source or Header  |  2016-03-02  |  38.3 KB  |  1,097 lines

  1. //***************************************************************************************
  2. // BlendApp.cpp by Frank Luna (C) 2015 All Rights Reserved.
  3. //***************************************************************************************
  4.  
  5. #include "../../Common/d3dApp.h"
  6. #include "../../Common/MathHelper.h"
  7. #include "../../Common/UploadBuffer.h"
  8. #include "../../Common/GeometryGenerator.h"
  9. #include "FrameResource.h"
  10. #include "Waves.h"
  11.  
  12. using Microsoft::WRL::ComPtr;
  13. using namespace DirectX;
  14. using namespace DirectX::PackedVector;
  15.  
  16. #pragma comment(lib, "d3dcompiler.lib")
  17. #pragma comment(lib, "D3D12.lib")
  18.  
  19. const int gNumFrameResources = 3;
  20.  
  21. // Lightweight structure stores parameters to draw a shape.  This will
  22. // vary from app-to-app.
  23. struct RenderItem
  24. {
  25.     RenderItem() = default;
  26.  
  27.     // World matrix of the shape that describes the object's local space
  28.     // relative to the world space, which defines the position, orientation,
  29.     // and scale of the object in the world.
  30.     XMFLOAT4X4 World = MathHelper::Identity4x4();
  31.  
  32.     XMFLOAT4X4 TexTransform = MathHelper::Identity4x4();
  33.  
  34.     // Dirty flag indicating the object data has changed and we need to update the constant buffer.
  35.     // Because we have an object cbuffer for each FrameResource, we have to apply the
  36.     // update to each FrameResource.  Thus, when we modify obect data we should set 
  37.     // NumFramesDirty = gNumFrameResources so that each frame resource gets the update.
  38.     int NumFramesDirty = gNumFrameResources;
  39.  
  40.     // Index into GPU constant buffer corresponding to the ObjectCB for this render item.
  41.     UINT ObjCBIndex = -1;
  42.  
  43.     Material* Mat = nullptr;
  44.     MeshGeometry* Geo = nullptr;
  45.  
  46.     // Primitive topology.
  47.     D3D12_PRIMITIVE_TOPOLOGY PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  48.  
  49.     // DrawIndexedInstanced parameters.
  50.     UINT IndexCount = 0;
  51.     UINT StartIndexLocation = 0;
  52.     int BaseVertexLocation = 0;
  53. };
  54.  
  55. enum class RenderLayer : int
  56. {
  57.     Opaque = 0,
  58.     Transparent,
  59.     AlphaTested,
  60.     Count
  61. };
  62.  
  63. class BlendApp : public D3DApp
  64. {
  65. public:
  66.     BlendApp(HINSTANCE hInstance);
  67.     BlendApp(const BlendApp& rhs) = delete;
  68.     BlendApp& operator=(const BlendApp& rhs) = delete;
  69.     ~BlendApp();
  70.  
  71.     virtual bool Initialize()override;
  72.  
  73. private:
  74.     virtual void OnResize()override;
  75.     virtual void Update(const GameTimer& gt)override;
  76.     virtual void Draw(const GameTimer& gt)override;
  77.  
  78.     virtual void OnMouseDown(WPARAM btnState, int x, int y)override;
  79.     virtual void OnMouseUp(WPARAM btnState, int x, int y)override;
  80.     virtual void OnMouseMove(WPARAM btnState, int x, int y)override;
  81.  
  82.     void OnKeyboardInput(const GameTimer& gt);
  83.     void UpdateCamera(const GameTimer& gt);
  84.     void AnimateMaterials(const GameTimer& gt);
  85.     void UpdateObjectCBs(const GameTimer& gt);
  86.     void UpdateMaterialCBs(const GameTimer& gt);
  87.     void UpdateMainPassCB(const GameTimer& gt);
  88.     void UpdateWaves(const GameTimer& gt); 
  89.  
  90.     void LoadTextures();
  91.     void BuildRootSignature();
  92.     void BuildDescriptorHeaps();
  93.     void BuildShadersAndInputLayout();
  94.     void BuildLandGeometry();
  95.     void BuildWavesGeometry();
  96.     void BuildBoxGeometry();
  97.     void BuildPSOs();
  98.     void BuildFrameResources();
  99.     void BuildMaterials();
  100.     void BuildRenderItems();
  101.     void DrawRenderItems(ID3D12GraphicsCommandList* cmdList, const std::vector<RenderItem*>& ritems);
  102.  
  103.     std::array<const CD3DX12_STATIC_SAMPLER_DESC, 6> GetStaticSamplers();
  104.  
  105.     float GetHillsHeight(float x, float z)const;
  106.     XMFLOAT3 GetHillsNormal(float x, float z)const;
  107.  
  108. private:
  109.  
  110.     std::vector<std::unique_ptr<FrameResource>> mFrameResources;
  111.     FrameResource* mCurrFrameResource = nullptr;
  112.     int mCurrFrameResourceIndex = 0;
  113.  
  114.     UINT mCbvSrvDescriptorSize = 0;
  115.  
  116.     ComPtr<ID3D12RootSignature> mRootSignature = nullptr;
  117.  
  118.     ComPtr<ID3D12DescriptorHeap> mSrvDescriptorHeap = nullptr;
  119.  
  120.     std::unordered_map<std::string, std::unique_ptr<MeshGeometry>> mGeometries;
  121.     std::unordered_map<std::string, std::unique_ptr<Material>> mMaterials;
  122.     std::unordered_map<std::string, std::unique_ptr<Texture>> mTextures;
  123.     std::unordered_map<std::string, ComPtr<ID3DBlob>> mShaders;
  124.     std::unordered_map<std::string, ComPtr<ID3D12PipelineState>> mPSOs;
  125.  
  126.     std::vector<D3D12_INPUT_ELEMENT_DESC> mInputLayout;
  127.  
  128.     RenderItem* mWavesRitem = nullptr;
  129.  
  130.     // List of all the render items.
  131.     std::vector<std::unique_ptr<RenderItem>> mAllRitems;
  132.  
  133.     // Render items divided by PSO.
  134.     std::vector<RenderItem*> mRitemLayer[(int)RenderLayer::Count];
  135.  
  136.     std::unique_ptr<Waves> mWaves;
  137.  
  138.     PassConstants mMainPassCB;
  139.  
  140.     XMFLOAT3 mEyePos = { 0.0f, 0.0f, 0.0f };
  141.     XMFLOAT4X4 mView = MathHelper::Identity4x4();
  142.     XMFLOAT4X4 mProj = MathHelper::Identity4x4();
  143.  
  144.     float mTheta = 1.5f*XM_PI;
  145.     float mPhi = XM_PIDIV2 - 0.1f;
  146.     float mRadius = 50.0f;
  147.  
  148.     POINT mLastMousePos;
  149. };
  150.  
  151. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
  152.     PSTR cmdLine, int showCmd)
  153. {
  154.     // Enable run-time memory check for debug builds.
  155. #if defined(DEBUG) | defined(_DEBUG)
  156.     _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  157. #endif
  158.  
  159.     try
  160.     {
  161.         BlendApp theApp(hInstance);
  162.         if(!theApp.Initialize())
  163.             return 0;
  164.  
  165.         return theApp.Run();
  166.     }
  167.     catch(DxException& e)
  168.     {
  169.         MessageBox(nullptr, e.ToString().c_str(), L"HR Failed", MB_OK);
  170.         return 0;
  171.     }
  172. }
  173.  
  174. BlendApp::BlendApp(HINSTANCE hInstance)
  175.     : D3DApp(hInstance)
  176. {
  177. }
  178.  
  179. BlendApp::~BlendApp()
  180. {
  181.     if(md3dDevice != nullptr)
  182.         FlushCommandQueue();
  183. }
  184.  
  185. bool BlendApp::Initialize()
  186. {
  187.     if(!D3DApp::Initialize())
  188.         return false;
  189.  
  190.     // Reset the command list to prep for initialization commands.
  191.     ThrowIfFailed(mCommandList->Reset(mDirectCmdListAlloc.Get(), nullptr));
  192.  
  193.     // Get the increment size of a descriptor in this heap type.  This is hardware specific, 
  194.     // so we have to query this information.
  195.     mCbvSrvDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  196.  
  197.     mWaves = std::make_unique<Waves>(128, 128, 1.0f, 0.03f, 4.0f, 0.2f);
  198.  
  199.     LoadTextures();
  200.     BuildRootSignature();
  201.     BuildDescriptorHeaps();
  202.     BuildShadersAndInputLayout();
  203.     BuildLandGeometry();
  204.     BuildWavesGeometry();
  205.     BuildBoxGeometry();
  206.     BuildMaterials();
  207.     BuildRenderItems();
  208.     BuildFrameResources();
  209.     BuildPSOs();
  210.  
  211.     // Execute the initialization commands.
  212.     ThrowIfFailed(mCommandList->Close());
  213.     ID3D12CommandList* cmdsLists[] = { mCommandList.Get() };
  214.     mCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
  215.  
  216.     // Wait until initialization is complete.
  217.     FlushCommandQueue();
  218.  
  219.     return true;
  220. }
  221.  
  222. void BlendApp::OnResize()
  223. {
  224.     D3DApp::OnResize();
  225.  
  226.     // The window resized, so update the aspect ratio and recompute the projection matrix.
  227.     XMMATRIX P = XMMatrixPerspectiveFovLH(0.25f*MathHelper::Pi, AspectRatio(), 1.0f, 1000.0f);
  228.     XMStoreFloat4x4(&mProj, P);
  229. }
  230.  
  231. void BlendApp::Update(const GameTimer& gt)
  232. {
  233.     OnKeyboardInput(gt);
  234.     UpdateCamera(gt);
  235.  
  236.     // Cycle through the circular frame resource array.
  237.     mCurrFrameResourceIndex = (mCurrFrameResourceIndex + 1) % gNumFrameResources;
  238.     mCurrFrameResource = mFrameResources[mCurrFrameResourceIndex].get();
  239.  
  240.     // Has the GPU finished processing the commands of the current frame resource?
  241.     // If not, wait until the GPU has completed commands up to this fence point.
  242.     if(mCurrFrameResource->Fence != 0 && mFence->GetCompletedValue() < mCurrFrameResource->Fence)
  243.     {
  244.         HANDLE eventHandle = CreateEventEx(nullptr, false, false, EVENT_ALL_ACCESS);
  245.         ThrowIfFailed(mFence->SetEventOnCompletion(mCurrFrameResource->Fence, eventHandle));
  246.         WaitForSingleObject(eventHandle, INFINITE);
  247.         CloseHandle(eventHandle);
  248.     }
  249.  
  250.     AnimateMaterials(gt);
  251.     UpdateObjectCBs(gt);
  252.     UpdateMaterialCBs(gt);
  253.     UpdateMainPassCB(gt);
  254.     UpdateWaves(gt);
  255. }
  256.  
  257. void BlendApp::Draw(const GameTimer& gt)
  258. {
  259.     auto cmdListAlloc = mCurrFrameResource->CmdListAlloc;
  260.  
  261.     // Reuse the memory associated with command recording.
  262.     // We can only reset when the associated command lists have finished execution on the GPU.
  263.     ThrowIfFailed(cmdListAlloc->Reset());
  264.  
  265.     // A command list can be reset after it has been added to the command queue via ExecuteCommandList.
  266.     // Reusing the command list reuses memory.
  267.     ThrowIfFailed(mCommandList->Reset(cmdListAlloc.Get(), mPSOs["opaque"].Get()));
  268.  
  269.     mCommandList->RSSetViewports(1, &mScreenViewport);
  270.     mCommandList->RSSetScissorRects(1, &mScissorRect);
  271.  
  272.     // Indicate a state transition on the resource usage.
  273.     mCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(),
  274.         D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET));
  275.  
  276.     // Clear the back buffer and depth buffer.
  277.     mCommandList->ClearRenderTargetView(CurrentBackBufferView(), (float*)&mMainPassCB.FogColor, 0, nullptr);
  278.     mCommandList->ClearDepthStencilView(DepthStencilView(), D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr);
  279.  
  280.     // Specify the buffers we are going to render to.
  281.     mCommandList->OMSetRenderTargets(1, &CurrentBackBufferView(), true, &DepthStencilView());
  282.  
  283.     ID3D12DescriptorHeap* descriptorHeaps[] = { mSrvDescriptorHeap.Get() };
  284.     mCommandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps);
  285.  
  286.     mCommandList->SetGraphicsRootSignature(mRootSignature.Get());
  287.  
  288.     auto passCB = mCurrFrameResource->PassCB->Resource();
  289.     mCommandList->SetGraphicsRootConstantBufferView(2, passCB->GetGPUVirtualAddress());
  290.  
  291.     DrawRenderItems(mCommandList.Get(), mRitemLayer[(int)RenderLayer::Opaque]);
  292.  
  293.     mCommandList->SetPipelineState(mPSOs["alphaTested"].Get());
  294.     DrawRenderItems(mCommandList.Get(), mRitemLayer[(int)RenderLayer::AlphaTested]);
  295.  
  296.     mCommandList->SetPipelineState(mPSOs["transparent"].Get());
  297.     DrawRenderItems(mCommandList.Get(), mRitemLayer[(int)RenderLayer::Transparent]);
  298.  
  299.     // Indicate a state transition on the resource usage.
  300.     mCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(),
  301.         D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT));
  302.  
  303.     // Done recording commands.
  304.     ThrowIfFailed(mCommandList->Close());
  305.  
  306.     // Add the command list to the queue for execution.
  307.     ID3D12CommandList* cmdsLists[] = { mCommandList.Get() };
  308.     mCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
  309.  
  310.     // Swap the back and front buffers
  311.     ThrowIfFailed(mSwapChain->Present(0, 0));
  312.     mCurrBackBuffer = (mCurrBackBuffer + 1) % SwapChainBufferCount;
  313.  
  314.     // Advance the fence value to mark commands up to this fence point.
  315.     mCurrFrameResource->Fence = ++mCurrentFence;
  316.  
  317.  
  318.     // Add an instruction to the command queue to set a new fence point. 
  319.     // Because we are on the GPU timeline, the new fence point won't be 
  320.     // set until the GPU finishes processing all the commands prior to this Signal().
  321.     mCommandQueue->Signal(mFence.Get(), mCurrentFence);
  322. }
  323.  
  324. void BlendApp::OnMouseDown(WPARAM btnState, int x, int y)
  325. {
  326.     mLastMousePos.x = x;
  327.     mLastMousePos.y = y;
  328.  
  329.     SetCapture(mhMainWnd);
  330. }
  331.  
  332. void BlendApp::OnMouseUp(WPARAM btnState, int x, int y)
  333. {
  334.     ReleaseCapture();
  335. }
  336.  
  337. void BlendApp::OnMouseMove(WPARAM btnState, int x, int y)
  338. {
  339.     if((btnState & MK_LBUTTON) != 0)
  340.     {
  341.         // Make each pixel correspond to a quarter of a degree.
  342.         float dx = XMConvertToRadians(0.25f*static_cast<float>(x - mLastMousePos.x));
  343.         float dy = XMConvertToRadians(0.25f*static_cast<float>(y - mLastMousePos.y));
  344.  
  345.         // Update angles based on input to orbit camera around box.
  346.         mTheta += dx;
  347.         mPhi += dy;
  348.  
  349.         // Restrict the angle mPhi.
  350.         mPhi = MathHelper::Clamp(mPhi, 0.1f, MathHelper::Pi - 0.1f);
  351.     }
  352.     else if((btnState & MK_RBUTTON) != 0)
  353.     {
  354.         // Make each pixel correspond to 0.2 unit in the scene.
  355.         float dx = 0.2f*static_cast<float>(x - mLastMousePos.x);
  356.         float dy = 0.2f*static_cast<float>(y - mLastMousePos.y);
  357.  
  358.         // Update the camera radius based on input.
  359.         mRadius += dx - dy;
  360.  
  361.         // Restrict the radius.
  362.         mRadius = MathHelper::Clamp(mRadius, 5.0f, 150.0f);
  363.     }
  364.  
  365.     mLastMousePos.x = x;
  366.     mLastMousePos.y = y;
  367. }
  368.  
  369. void BlendApp::OnKeyboardInput(const GameTimer& gt)
  370. {
  371. }
  372.  
  373. void BlendApp::UpdateCamera(const GameTimer& gt)
  374. {
  375.     // Convert Spherical to Cartesian coordinates.
  376.     mEyePos.x = mRadius*sinf(mPhi)*cosf(mTheta);
  377.     mEyePos.z = mRadius*sinf(mPhi)*sinf(mTheta);
  378.     mEyePos.y = mRadius*cosf(mPhi);
  379.  
  380.     // Build the view matrix.
  381.     XMVECTOR pos = XMVectorSet(mEyePos.x, mEyePos.y, mEyePos.z, 1.0f);
  382.     XMVECTOR target = XMVectorZero();
  383.     XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
  384.  
  385.     XMMATRIX view = XMMatrixLookAtLH(pos, target, up);
  386.     XMStoreFloat4x4(&mView, view);
  387. }
  388.  
  389. void BlendApp::AnimateMaterials(const GameTimer& gt)
  390. {
  391.     // Scroll the water material texture coordinates.
  392.     auto waterMat = mMaterials["water"].get();
  393.  
  394.     float& tu = waterMat->MatTransform(3, 0);
  395.     float& tv = waterMat->MatTransform(3, 1);
  396.  
  397.     tu += 0.1f * gt.DeltaTime();
  398.     tv += 0.02f * gt.DeltaTime();
  399.  
  400.     if(tu >= 1.0f)
  401.         tu -= 1.0f;
  402.  
  403.     if(tv >= 1.0f)
  404.         tv -= 1.0f;
  405.  
  406.     waterMat->MatTransform(3, 0) = tu;
  407.     waterMat->MatTransform(3, 1) = tv;
  408.  
  409.     // Material has changed, so need to update cbuffer.
  410.     waterMat->NumFramesDirty = gNumFrameResources;
  411. }
  412.  
  413. void BlendApp::UpdateObjectCBs(const GameTimer& gt)
  414. {
  415.     auto currObjectCB = mCurrFrameResource->ObjectCB.get();
  416.     for(auto& e : mAllRitems)
  417.     {
  418.         // Only update the cbuffer data if the constants have changed.  
  419.         // This needs to be tracked per frame resource.
  420.         if(e->NumFramesDirty > 0)
  421.         {
  422.             XMMATRIX world = XMLoadFloat4x4(&e->World);
  423.             XMMATRIX texTransform = XMLoadFloat4x4(&e->TexTransform);
  424.  
  425.             ObjectConstants objConstants;
  426.             XMStoreFloat4x4(&objConstants.World, XMMatrixTranspose(world));
  427.             XMStoreFloat4x4(&objConstants.TexTransform, XMMatrixTranspose(texTransform));
  428.  
  429.             currObjectCB->CopyData(e->ObjCBIndex, objConstants);
  430.  
  431.             // Next FrameResource need to be updated too.
  432.             e->NumFramesDirty--;
  433.         }
  434.     }
  435. }
  436.  
  437. void BlendApp::UpdateMaterialCBs(const GameTimer& gt)
  438. {
  439.     auto currMaterialCB = mCurrFrameResource->MaterialCB.get();
  440.     for(auto& e : mMaterials)
  441.     {
  442.         // Only update the cbuffer data if the constants have changed.  If the cbuffer
  443.         // data changes, it needs to be updated for each FrameResource.
  444.         Material* mat = e.second.get();
  445.         if(mat->NumFramesDirty > 0)
  446.         {
  447.             XMMATRIX matTransform = XMLoadFloat4x4(&mat->MatTransform);
  448.  
  449.             MaterialConstants matConstants;
  450.             matConstants.DiffuseAlbedo = mat->DiffuseAlbedo;
  451.             matConstants.FresnelR0 = mat->FresnelR0;
  452.             matConstants.Roughness = mat->Roughness;
  453.             XMStoreFloat4x4(&matConstants.MatTransform, XMMatrixTranspose(matTransform));
  454.  
  455.             currMaterialCB->CopyData(mat->MatCBIndex, matConstants);
  456.  
  457.             // Next FrameResource need to be updated too.
  458.             mat->NumFramesDirty--;
  459.         }
  460.     }
  461. }
  462.  
  463. void BlendApp::UpdateMainPassCB(const GameTimer& gt)
  464. {
  465.     XMMATRIX view = XMLoadFloat4x4(&mView);
  466.     XMMATRIX proj = XMLoadFloat4x4(&mProj);
  467.  
  468.     XMMATRIX viewProj = XMMatrixMultiply(view, proj);
  469.     XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(view), view);
  470.     XMMATRIX invProj = XMMatrixInverse(&XMMatrixDeterminant(proj), proj);
  471.     XMMATRIX invViewProj = XMMatrixInverse(&XMMatrixDeterminant(viewProj), viewProj);
  472.  
  473.     XMStoreFloat4x4(&mMainPassCB.View, XMMatrixTranspose(view));
  474.     XMStoreFloat4x4(&mMainPassCB.InvView, XMMatrixTranspose(invView));
  475.     XMStoreFloat4x4(&mMainPassCB.Proj, XMMatrixTranspose(proj));
  476.     XMStoreFloat4x4(&mMainPassCB.InvProj, XMMatrixTranspose(invProj));
  477.     XMStoreFloat4x4(&mMainPassCB.ViewProj, XMMatrixTranspose(viewProj));
  478.     XMStoreFloat4x4(&mMainPassCB.InvViewProj, XMMatrixTranspose(invViewProj));
  479.     mMainPassCB.EyePosW = mEyePos;
  480.     mMainPassCB.RenderTargetSize = XMFLOAT2((float)mClientWidth, (float)mClientHeight);
  481.     mMainPassCB.InvRenderTargetSize = XMFLOAT2(1.0f / mClientWidth, 1.0f / mClientHeight);
  482.     mMainPassCB.NearZ = 1.0f;
  483.     mMainPassCB.FarZ = 1000.0f;
  484.     mMainPassCB.TotalTime = gt.TotalTime();
  485.     mMainPassCB.DeltaTime = gt.DeltaTime();
  486.     mMainPassCB.AmbientLight = { 0.25f, 0.25f, 0.35f, 1.0f };
  487.     mMainPassCB.Lights[0].Direction = { 0.57735f, -0.57735f, 0.57735f };
  488.     mMainPassCB.Lights[0].Strength = { 0.9f, 0.9f, 0.8f };
  489.     mMainPassCB.Lights[1].Direction = { -0.57735f, -0.57735f, 0.57735f };
  490.     mMainPassCB.Lights[1].Strength = { 0.3f, 0.3f, 0.3f };
  491.     mMainPassCB.Lights[2].Direction = { 0.0f, -0.707f, -0.707f };
  492.     mMainPassCB.Lights[2].Strength = { 0.15f, 0.15f, 0.15f };
  493.  
  494.     auto currPassCB = mCurrFrameResource->PassCB.get();
  495.     currPassCB->CopyData(0, mMainPassCB);
  496. }
  497.  
  498. void BlendApp::UpdateWaves(const GameTimer& gt)
  499. {
  500.     // Every quarter second, generate a random wave.
  501.     static float t_base = 0.0f;
  502.     if((mTimer.TotalTime() - t_base) >= 0.25f)
  503.     {
  504.         t_base += 0.25f;
  505.  
  506.         int i = MathHelper::Rand(4, mWaves->RowCount() - 5);
  507.         int j = MathHelper::Rand(4, mWaves->ColumnCount() - 5);
  508.  
  509.         float r = MathHelper::RandF(0.2f, 0.5f);
  510.  
  511.         mWaves->Disturb(i, j, r);
  512.     }
  513.  
  514.     // Update the wave simulation.
  515.     mWaves->Update(gt.DeltaTime());
  516.  
  517.     // Update the wave vertex buffer with the new solution.
  518.     auto currWavesVB = mCurrFrameResource->WavesVB.get();
  519.     for(int i = 0; i < mWaves->VertexCount(); ++i)
  520.     {
  521.         Vertex v;
  522.  
  523.         v.Pos = mWaves->Position(i);
  524.         v.Normal = mWaves->Normal(i);
  525.         
  526.         // Derive tex-coords from position by 
  527.         // mapping [-w/2,w/2] --> [0,1]
  528.         v.TexC.x = 0.5f + v.Pos.x / mWaves->Width();
  529.         v.TexC.y = 0.5f - v.Pos.z / mWaves->Depth();
  530.  
  531.         currWavesVB->CopyData(i, v);
  532.     }
  533.  
  534.     // Set the dynamic VB of the wave renderitem to the current frame VB.
  535.     mWavesRitem->Geo->VertexBufferGPU = currWavesVB->Resource();
  536. }
  537.  
  538. void BlendApp::LoadTextures()
  539. {
  540.     auto grassTex = std::make_unique<Texture>();
  541.     grassTex->Name = "grassTex";
  542.     grassTex->Filename = L"../../Textures/grass.dds";
  543.     ThrowIfFailed(DirectX::CreateDDSTextureFromFile12(md3dDevice.Get(),
  544.         mCommandList.Get(), grassTex->Filename.c_str(),
  545.         grassTex->Resource, grassTex->UploadHeap));
  546.  
  547.     auto waterTex = std::make_unique<Texture>();
  548.     waterTex->Name = "waterTex";
  549.     waterTex->Filename = L"../../Textures/water1.dds";
  550.     ThrowIfFailed(DirectX::CreateDDSTextureFromFile12(md3dDevice.Get(),
  551.         mCommandList.Get(), waterTex->Filename.c_str(),
  552.         waterTex->Resource, waterTex->UploadHeap));
  553.  
  554.     auto fenceTex = std::make_unique<Texture>();
  555.     fenceTex->Name = "fenceTex";
  556.     fenceTex->Filename = L"../../Textures/WireFence.dds";
  557.     ThrowIfFailed(DirectX::CreateDDSTextureFromFile12(md3dDevice.Get(),
  558.         mCommandList.Get(), fenceTex->Filename.c_str(),
  559.         fenceTex->Resource, fenceTex->UploadHeap));
  560.  
  561.     mTextures[grassTex->Name] = std::move(grassTex);
  562.     mTextures[waterTex->Name] = std::move(waterTex);
  563.     mTextures[fenceTex->Name] = std::move(fenceTex);
  564. }
  565.  
  566. void BlendApp::BuildRootSignature()
  567. {
  568.     CD3DX12_DESCRIPTOR_RANGE texTable;
  569.     texTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0);
  570.  
  571.     // Root parameter can be a table, root descriptor or root constants.
  572.     CD3DX12_ROOT_PARAMETER slotRootParameter[4];
  573.  
  574.     // Perfomance TIP: Order from most frequent to least frequent.
  575.     slotRootParameter[0].InitAsDescriptorTable(1, &texTable, D3D12_SHADER_VISIBILITY_PIXEL);
  576.     slotRootParameter[1].InitAsConstantBufferView(0);
  577.     slotRootParameter[2].InitAsConstantBufferView(1);
  578.     slotRootParameter[3].InitAsConstantBufferView(2);
  579.  
  580.     auto staticSamplers = GetStaticSamplers();
  581.  
  582.     // A root signature is an array of root parameters.
  583.     CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(4, slotRootParameter,
  584.         (UINT)staticSamplers.size(), staticSamplers.data(),
  585.         D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  586.  
  587.     // create a root signature with a single slot which points to a descriptor range consisting of a single constant buffer
  588.     ComPtr<ID3DBlob> serializedRootSig = nullptr;
  589.     ComPtr<ID3DBlob> errorBlob = nullptr;
  590.     HRESULT hr = D3D12SerializeRootSignature(&rootSigDesc, D3D_ROOT_SIGNATURE_VERSION_1,
  591.         serializedRootSig.GetAddressOf(), errorBlob.GetAddressOf());
  592.  
  593.     if(errorBlob != nullptr)
  594.     {
  595.         ::OutputDebugStringA((char*)errorBlob->GetBufferPointer());
  596.     }
  597.     ThrowIfFailed(hr);
  598.  
  599.     ThrowIfFailed(md3dDevice->CreateRootSignature(
  600.         0,
  601.         serializedRootSig->GetBufferPointer(),
  602.         serializedRootSig->GetBufferSize(),
  603.         IID_PPV_ARGS(mRootSignature.GetAddressOf())));
  604. }
  605.  
  606. void BlendApp::BuildDescriptorHeaps()
  607. {
  608.     //
  609.     // Create the SRV heap.
  610.     //
  611.     D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = {};
  612.     srvHeapDesc.NumDescriptors = 3;
  613.     srvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  614.     srvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  615.     ThrowIfFailed(md3dDevice->CreateDescriptorHeap(&srvHeapDesc, IID_PPV_ARGS(&mSrvDescriptorHeap)));
  616.  
  617.     //
  618.     // Fill out the heap with actual descriptors.
  619.     //
  620.     CD3DX12_CPU_DESCRIPTOR_HANDLE hDescriptor(mSrvDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
  621.  
  622.     auto grassTex = mTextures["grassTex"]->Resource;
  623.     auto waterTex = mTextures["waterTex"]->Resource;
  624.     auto fenceTex = mTextures["fenceTex"]->Resource;
  625.  
  626.     D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
  627.     srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  628.     srvDesc.Format = grassTex->GetDesc().Format;
  629.     srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  630.     srvDesc.Texture2D.MostDetailedMip = 0;
  631.     srvDesc.Texture2D.MipLevels = -1;
  632.     md3dDevice->CreateShaderResourceView(grassTex.Get(), &srvDesc, hDescriptor);
  633.  
  634.     // next descriptor
  635.     hDescriptor.Offset(1, mCbvSrvDescriptorSize);
  636.  
  637.     srvDesc.Format = waterTex->GetDesc().Format;
  638.     md3dDevice->CreateShaderResourceView(waterTex.Get(), &srvDesc, hDescriptor);
  639.  
  640.     // next descriptor
  641.     hDescriptor.Offset(1, mCbvSrvDescriptorSize);
  642.  
  643.     srvDesc.Format = fenceTex->GetDesc().Format;
  644.     md3dDevice->CreateShaderResourceView(fenceTex.Get(), &srvDesc, hDescriptor);
  645. }
  646.  
  647. void BlendApp::BuildShadersAndInputLayout()
  648. {
  649.     const D3D_SHADER_MACRO defines[] =
  650.     {
  651.         "FOG", "1",
  652.         NULL, NULL
  653.     };
  654.  
  655.     const D3D_SHADER_MACRO alphaTestDefines[] =
  656.     {
  657.         "FOG", "1",
  658.         "ALPHA_TEST", "1",
  659.         NULL, NULL
  660.     };
  661.  
  662.     mShaders["standardVS"] = d3dUtil::CompileShader(L"Shaders\\Default.hlsl", nullptr, "VS", "vs_5_0");
  663.     mShaders["opaquePS"] = d3dUtil::CompileShader(L"Shaders\\Default.hlsl", defines, "PS", "ps_5_0");
  664.     mShaders["alphaTestedPS"] = d3dUtil::CompileShader(L"Shaders\\Default.hlsl", alphaTestDefines, "PS", "ps_5_0");
  665.     
  666.     mInputLayout =
  667.     {
  668.         { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  669.         { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  670.         { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  671.     };
  672. }
  673.  
  674. void BlendApp::BuildLandGeometry()
  675. {
  676.     GeometryGenerator geoGen;
  677.     GeometryGenerator::MeshData grid = geoGen.CreateGrid(160.0f, 160.0f, 50, 50);
  678.  
  679.     //
  680.     // Extract the vertex elements we are interested and apply the height function to
  681.     // each vertex.  In addition, color the vertices based on their height so we have
  682.     // sandy looking beaches, grassy low hills, and snow mountain peaks.
  683.     //
  684.  
  685.     std::vector<Vertex> vertices(grid.Vertices.size());
  686.     for(size_t i = 0; i < grid.Vertices.size(); ++i)
  687.     {
  688.         auto& p = grid.Vertices[i].Position;
  689.         vertices[i].Pos = p;
  690.         vertices[i].Pos.y = GetHillsHeight(p.x, p.z);
  691.         vertices[i].Normal = GetHillsNormal(p.x, p.z);
  692.         vertices[i].TexC = grid.Vertices[i].TexC;
  693.     }
  694.  
  695.     const UINT vbByteSize = (UINT)vertices.size() * sizeof(Vertex);
  696.  
  697.     std::vector<std::uint16_t> indices = grid.GetIndices16();
  698.     const UINT ibByteSize = (UINT)indices.size() * sizeof(std::uint16_t);
  699.  
  700.     auto geo = std::make_unique<MeshGeometry>();
  701.     geo->Name = "landGeo";
  702.  
  703.     ThrowIfFailed(D3DCreateBlob(vbByteSize, &geo->VertexBufferCPU));
  704.     CopyMemory(geo->VertexBufferCPU->GetBufferPointer(), vertices.data(), vbByteSize);
  705.  
  706.     ThrowIfFailed(D3DCreateBlob(ibByteSize, &geo->IndexBufferCPU));
  707.     CopyMemory(geo->IndexBufferCPU->GetBufferPointer(), indices.data(), ibByteSize);
  708.  
  709.     geo->VertexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
  710.         mCommandList.Get(), vertices.data(), vbByteSize, geo->VertexBufferUploader);
  711.  
  712.     geo->IndexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
  713.         mCommandList.Get(), indices.data(), ibByteSize, geo->IndexBufferUploader);
  714.  
  715.     geo->VertexByteStride = sizeof(Vertex);
  716.     geo->VertexBufferByteSize = vbByteSize;
  717.     geo->IndexFormat = DXGI_FORMAT_R16_UINT;
  718.     geo->IndexBufferByteSize = ibByteSize;
  719.  
  720.     SubmeshGeometry submesh;
  721.     submesh.IndexCount = (UINT)indices.size();
  722.     submesh.StartIndexLocation = 0;
  723.     submesh.BaseVertexLocation = 0;
  724.  
  725.     geo->DrawArgs["grid"] = submesh;
  726.  
  727.     mGeometries["landGeo"] = std::move(geo);
  728. }
  729.  
  730. void BlendApp::BuildWavesGeometry()
  731. {
  732.     std::vector<std::uint16_t> indices(3 * mWaves->TriangleCount()); // 3 indices per face
  733.     assert(mWaves->VertexCount() < 0x0000ffff);
  734.  
  735.     // Iterate over each quad.
  736.     int m = mWaves->RowCount();
  737.     int n = mWaves->ColumnCount();
  738.     int k = 0;
  739.     for(int i = 0; i < m - 1; ++i)
  740.     {
  741.         for(int j = 0; j < n - 1; ++j)
  742.         {
  743.             indices[k] = i*n + j;
  744.             indices[k + 1] = i*n + j + 1;
  745.             indices[k + 2] = (i + 1)*n + j;
  746.  
  747.             indices[k + 3] = (i + 1)*n + j;
  748.             indices[k + 4] = i*n + j + 1;
  749.             indices[k + 5] = (i + 1)*n + j + 1;
  750.  
  751.             k += 6; // next quad
  752.         }
  753.     }
  754.  
  755.     UINT vbByteSize = mWaves->VertexCount()*sizeof(Vertex);
  756.     UINT ibByteSize = (UINT)indices.size()*sizeof(std::uint16_t);
  757.  
  758.     auto geo = std::make_unique<MeshGeometry>();
  759.     geo->Name = "waterGeo";
  760.  
  761.     // Set dynamically.
  762.     geo->VertexBufferCPU = nullptr;
  763.     geo->VertexBufferGPU = nullptr;
  764.  
  765.     ThrowIfFailed(D3DCreateBlob(ibByteSize, &geo->IndexBufferCPU));
  766.     CopyMemory(geo->IndexBufferCPU->GetBufferPointer(), indices.data(), ibByteSize);
  767.  
  768.     geo->IndexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
  769.         mCommandList.Get(), indices.data(), ibByteSize, geo->IndexBufferUploader);
  770.  
  771.     geo->VertexByteStride = sizeof(Vertex);
  772.     geo->VertexBufferByteSize = vbByteSize;
  773.     geo->IndexFormat = DXGI_FORMAT_R16_UINT;
  774.     geo->IndexBufferByteSize = ibByteSize;
  775.  
  776.     SubmeshGeometry submesh;
  777.     submesh.IndexCount = (UINT)indices.size();
  778.     submesh.StartIndexLocation = 0;
  779.     submesh.BaseVertexLocation = 0;
  780.  
  781.     geo->DrawArgs["grid"] = submesh;
  782.  
  783.     mGeometries["waterGeo"] = std::move(geo);
  784. }
  785.  
  786. void BlendApp::BuildBoxGeometry()
  787. {
  788.     GeometryGenerator geoGen;
  789.     GeometryGenerator::MeshData box = geoGen.CreateBox(8.0f, 8.0f, 8.0f, 3);
  790.  
  791.     std::vector<Vertex> vertices(box.Vertices.size());
  792.     for (size_t i = 0; i < box.Vertices.size(); ++i)
  793.     {
  794.         auto& p = box.Vertices[i].Position;
  795.         vertices[i].Pos = p;
  796.         vertices[i].Normal = box.Vertices[i].Normal;
  797.         vertices[i].TexC = box.Vertices[i].TexC;
  798.     }
  799.  
  800.     const UINT vbByteSize = (UINT)vertices.size() * sizeof(Vertex);
  801.  
  802.     std::vector<std::uint16_t> indices = box.GetIndices16();
  803.     const UINT ibByteSize = (UINT)indices.size() * sizeof(std::uint16_t);
  804.  
  805.     auto geo = std::make_unique<MeshGeometry>();
  806.     geo->Name = "boxGeo";
  807.  
  808.     ThrowIfFailed(D3DCreateBlob(vbByteSize, &geo->VertexBufferCPU));
  809.     CopyMemory(geo->VertexBufferCPU->GetBufferPointer(), vertices.data(), vbByteSize);
  810.  
  811.     ThrowIfFailed(D3DCreateBlob(ibByteSize, &geo->IndexBufferCPU));
  812.     CopyMemory(geo->IndexBufferCPU->GetBufferPointer(), indices.data(), ibByteSize);
  813.  
  814.     geo->VertexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
  815.         mCommandList.Get(), vertices.data(), vbByteSize, geo->VertexBufferUploader);
  816.  
  817.     geo->IndexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
  818.         mCommandList.Get(), indices.data(), ibByteSize, geo->IndexBufferUploader);
  819.  
  820.     geo->VertexByteStride = sizeof(Vertex);
  821.     geo->VertexBufferByteSize = vbByteSize;
  822.     geo->IndexFormat = DXGI_FORMAT_R16_UINT;
  823.     geo->IndexBufferByteSize = ibByteSize;
  824.  
  825.     SubmeshGeometry submesh;
  826.     submesh.IndexCount = (UINT)indices.size();
  827.     submesh.StartIndexLocation = 0;
  828.     submesh.BaseVertexLocation = 0;
  829.  
  830.     geo->DrawArgs["box"] = submesh;
  831.  
  832.     mGeometries["boxGeo"] = std::move(geo);
  833. }
  834.  
  835. void BlendApp::BuildPSOs()
  836. {
  837.     D3D12_GRAPHICS_PIPELINE_STATE_DESC opaquePsoDesc;
  838.  
  839.     //
  840.     // PSO for opaque objects.
  841.     //
  842.     ZeroMemory(&opaquePsoDesc, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
  843.     opaquePsoDesc.InputLayout = { mInputLayout.data(), (UINT)mInputLayout.size() };
  844.     opaquePsoDesc.pRootSignature = mRootSignature.Get();
  845.     opaquePsoDesc.VS = 
  846.     { 
  847.         reinterpret_cast<BYTE*>(mShaders["standardVS"]->GetBufferPointer()), 
  848.         mShaders["standardVS"]->GetBufferSize()
  849.     };
  850.     opaquePsoDesc.PS = 
  851.     { 
  852.         reinterpret_cast<BYTE*>(mShaders["opaquePS"]->GetBufferPointer()),
  853.         mShaders["opaquePS"]->GetBufferSize()
  854.     };
  855.     opaquePsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
  856.     opaquePsoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
  857.     opaquePsoDesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT);
  858.     opaquePsoDesc.SampleMask = UINT_MAX;
  859.     opaquePsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  860.     opaquePsoDesc.NumRenderTargets = 1;
  861.     opaquePsoDesc.RTVFormats[0] = mBackBufferFormat;
  862.     opaquePsoDesc.SampleDesc.Count = m4xMsaaState ? 4 : 1;
  863.     opaquePsoDesc.SampleDesc.Quality = m4xMsaaState ? (m4xMsaaQuality - 1) : 0;
  864.     opaquePsoDesc.DSVFormat = mDepthStencilFormat;
  865.     ThrowIfFailed(md3dDevice->CreateGraphicsPipelineState(&opaquePsoDesc, IID_PPV_ARGS(&mPSOs["opaque"])));
  866.  
  867.     //
  868.     // PSO for transparent objects
  869.     //
  870.  
  871.     D3D12_GRAPHICS_PIPELINE_STATE_DESC transparentPsoDesc = opaquePsoDesc;
  872.  
  873.     D3D12_RENDER_TARGET_BLEND_DESC transparencyBlendDesc;
  874.     transparencyBlendDesc.BlendEnable = true;
  875.     transparencyBlendDesc.LogicOpEnable = false;
  876.     transparencyBlendDesc.SrcBlend = D3D12_BLEND_SRC_ALPHA;
  877.     transparencyBlendDesc.DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  878.     transparencyBlendDesc.BlendOp = D3D12_BLEND_OP_ADD;
  879.     transparencyBlendDesc.SrcBlendAlpha = D3D12_BLEND_ONE;
  880.     transparencyBlendDesc.DestBlendAlpha = D3D12_BLEND_ZERO;
  881.     transparencyBlendDesc.BlendOpAlpha = D3D12_BLEND_OP_ADD;
  882.     transparencyBlendDesc.LogicOp = D3D12_LOGIC_OP_NOOP;
  883.     transparencyBlendDesc.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  884.  
  885.     transparentPsoDesc.BlendState.RenderTarget[0] = transparencyBlendDesc;
  886.     ThrowIfFailed(md3dDevice->CreateGraphicsPipelineState(&transparentPsoDesc, IID_PPV_ARGS(&mPSOs["transparent"])));
  887.  
  888.     //
  889.     // PSO for alpha tested objects
  890.     //
  891.  
  892.     D3D12_GRAPHICS_PIPELINE_STATE_DESC alphaTestedPsoDesc = opaquePsoDesc;
  893.     alphaTestedPsoDesc.PS = 
  894.     { 
  895.         reinterpret_cast<BYTE*>(mShaders["alphaTestedPS"]->GetBufferPointer()),
  896.         mShaders["alphaTestedPS"]->GetBufferSize()
  897.     };
  898.     alphaTestedPsoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
  899.     ThrowIfFailed(md3dDevice->CreateGraphicsPipelineState(&alphaTestedPsoDesc, IID_PPV_ARGS(&mPSOs["alphaTested"])));
  900. }
  901.  
  902. void BlendApp::BuildFrameResources()
  903. {
  904.     for(int i = 0; i < gNumFrameResources; ++i)
  905.     {
  906.         mFrameResources.push_back(std::make_unique<FrameResource>(md3dDevice.Get(),
  907.             1, (UINT)mAllRitems.size(), (UINT)mMaterials.size(), mWaves->VertexCount()));
  908.     }
  909. }
  910.  
  911. void BlendApp::BuildMaterials()
  912. {
  913.     auto grass = std::make_unique<Material>();
  914.     grass->Name = "grass";
  915.     grass->MatCBIndex = 0;
  916.     grass->DiffuseSrvHeapIndex = 0;
  917.     grass->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
  918.     grass->FresnelR0 = XMFLOAT3(0.01f, 0.01f, 0.01f);
  919.     grass->Roughness = 0.125f;
  920.  
  921.     // This is not a good water material definition, but we do not have all the rendering
  922.     // tools we need (transparency, environment reflection), so we fake it for now.
  923.     auto water = std::make_unique<Material>();
  924.     water->Name = "water";
  925.     water->MatCBIndex = 1;
  926.     water->DiffuseSrvHeapIndex = 1;
  927.     water->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 0.5f);
  928.     water->FresnelR0 = XMFLOAT3(0.1f, 0.1f, 0.1f);
  929.     water->Roughness = 0.0f;
  930.  
  931.     auto wirefence = std::make_unique<Material>();
  932.     wirefence->Name = "wirefence";
  933.     wirefence->MatCBIndex = 2;
  934.     wirefence->DiffuseSrvHeapIndex = 2;
  935.     wirefence->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
  936.     wirefence->FresnelR0 = XMFLOAT3(0.1f, 0.1f, 0.1f);
  937.     wirefence->Roughness = 0.25f;
  938.  
  939.     mMaterials["grass"] = std::move(grass);
  940.     mMaterials["water"] = std::move(water);
  941.     mMaterials["wirefence"] = std::move(wirefence);
  942. }
  943.  
  944. void BlendApp::BuildRenderItems()
  945. {
  946.     auto wavesRitem = std::make_unique<RenderItem>();
  947.     wavesRitem->World = MathHelper::Identity4x4();
  948.     XMStoreFloat4x4(&wavesRitem->TexTransform, XMMatrixScaling(5.0f, 5.0f, 1.0f));
  949.     wavesRitem->ObjCBIndex = 0;
  950.     wavesRitem->Mat = mMaterials["water"].get();
  951.     wavesRitem->Geo = mGeometries["waterGeo"].get();
  952.     wavesRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  953.     wavesRitem->IndexCount = wavesRitem->Geo->DrawArgs["grid"].IndexCount;
  954.     wavesRitem->StartIndexLocation = wavesRitem->Geo->DrawArgs["grid"].StartIndexLocation;
  955.     wavesRitem->BaseVertexLocation = wavesRitem->Geo->DrawArgs["grid"].BaseVertexLocation;
  956.  
  957.     mWavesRitem = wavesRitem.get();
  958.  
  959.     mRitemLayer[(int)RenderLayer::Transparent].push_back(wavesRitem.get());
  960.  
  961.     auto gridRitem = std::make_unique<RenderItem>();
  962.     gridRitem->World = MathHelper::Identity4x4();
  963.     XMStoreFloat4x4(&gridRitem->TexTransform, XMMatrixScaling(5.0f, 5.0f, 1.0f));
  964.     gridRitem->ObjCBIndex = 1;
  965.     gridRitem->Mat = mMaterials["grass"].get();
  966.     gridRitem->Geo = mGeometries["landGeo"].get();
  967.     gridRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  968.     gridRitem->IndexCount = gridRitem->Geo->DrawArgs["grid"].IndexCount;
  969.     gridRitem->StartIndexLocation = gridRitem->Geo->DrawArgs["grid"].StartIndexLocation;
  970.     gridRitem->BaseVertexLocation = gridRitem->Geo->DrawArgs["grid"].BaseVertexLocation;
  971.  
  972.     mRitemLayer[(int)RenderLayer::Opaque].push_back(gridRitem.get());
  973.  
  974.     auto boxRitem = std::make_unique<RenderItem>();
  975.     XMStoreFloat4x4(&boxRitem->World, XMMatrixTranslation(3.0f, 2.0f, -9.0f));
  976.     boxRitem->ObjCBIndex = 2;
  977.     boxRitem->Mat = mMaterials["wirefence"].get();
  978.     boxRitem->Geo = mGeometries["boxGeo"].get();
  979.     boxRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  980.     boxRitem->IndexCount = boxRitem->Geo->DrawArgs["box"].IndexCount;
  981.     boxRitem->StartIndexLocation = boxRitem->Geo->DrawArgs["box"].StartIndexLocation;
  982.     boxRitem->BaseVertexLocation = boxRitem->Geo->DrawArgs["box"].BaseVertexLocation;
  983.  
  984.     mRitemLayer[(int)RenderLayer::AlphaTested].push_back(boxRitem.get());
  985.  
  986.     mAllRitems.push_back(std::move(wavesRitem));
  987.     mAllRitems.push_back(std::move(gridRitem));
  988.     mAllRitems.push_back(std::move(boxRitem));
  989. }
  990.  
  991. void BlendApp::DrawRenderItems(ID3D12GraphicsCommandList* cmdList, const std::vector<RenderItem*>& ritems)
  992. {
  993.     UINT objCBByteSize = d3dUtil::CalcConstantBufferByteSize(sizeof(ObjectConstants));
  994.     UINT matCBByteSize = d3dUtil::CalcConstantBufferByteSize(sizeof(MaterialConstants));
  995.  
  996.     auto objectCB = mCurrFrameResource->ObjectCB->Resource();
  997.     auto matCB = mCurrFrameResource->MaterialCB->Resource();
  998.  
  999.     // For each render item...
  1000.     for(size_t i = 0; i < ritems.size(); ++i)
  1001.     {
  1002.         auto ri = ritems[i];
  1003.  
  1004.         cmdList->IASetVertexBuffers(0, 1, &ri->Geo->VertexBufferView());
  1005.         cmdList->IASetIndexBuffer(&ri->Geo->IndexBufferView());
  1006.         cmdList->IASetPrimitiveTopology(ri->PrimitiveType);
  1007.  
  1008.         CD3DX12_GPU_DESCRIPTOR_HANDLE tex(mSrvDescriptorHeap->GetGPUDescriptorHandleForHeapStart());
  1009.         tex.Offset(ri->Mat->DiffuseSrvHeapIndex, mCbvSrvDescriptorSize);
  1010.  
  1011.         D3D12_GPU_VIRTUAL_ADDRESS objCBAddress = objectCB->GetGPUVirtualAddress() + ri->ObjCBIndex*objCBByteSize;
  1012.         D3D12_GPU_VIRTUAL_ADDRESS matCBAddress = matCB->GetGPUVirtualAddress() + ri->Mat->MatCBIndex*matCBByteSize;
  1013.  
  1014.         cmdList->SetGraphicsRootDescriptorTable(0, tex);
  1015.         cmdList->SetGraphicsRootConstantBufferView(1, objCBAddress);
  1016.         cmdList->SetGraphicsRootConstantBufferView(3, matCBAddress);
  1017.  
  1018.         cmdList->DrawIndexedInstanced(ri->IndexCount, 1, ri->StartIndexLocation, ri->BaseVertexLocation, 0);
  1019.     }
  1020. }
  1021.  
  1022. std::array<const CD3DX12_STATIC_SAMPLER_DESC, 6> BlendApp::GetStaticSamplers()
  1023. {
  1024.     // Applications usually only need a handful of samplers.  So just define them all up front
  1025.     // and keep them available as part of the root signature.  
  1026.  
  1027.     const CD3DX12_STATIC_SAMPLER_DESC pointWrap(
  1028.         0, // shaderRegister
  1029.         D3D12_FILTER_MIN_MAG_MIP_POINT, // filter
  1030.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressU
  1031.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressV
  1032.         D3D12_TEXTURE_ADDRESS_MODE_WRAP); // addressW
  1033.  
  1034.     const CD3DX12_STATIC_SAMPLER_DESC pointClamp(
  1035.         1, // shaderRegister
  1036.         D3D12_FILTER_MIN_MAG_MIP_POINT, // filter
  1037.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressU
  1038.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressV
  1039.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP); // addressW
  1040.  
  1041.     const CD3DX12_STATIC_SAMPLER_DESC linearWrap(
  1042.         2, // shaderRegister
  1043.         D3D12_FILTER_MIN_MAG_MIP_LINEAR, // filter
  1044.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressU
  1045.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressV
  1046.         D3D12_TEXTURE_ADDRESS_MODE_WRAP); // addressW
  1047.  
  1048.     const CD3DX12_STATIC_SAMPLER_DESC linearClamp(
  1049.         3, // shaderRegister
  1050.         D3D12_FILTER_MIN_MAG_MIP_LINEAR, // filter
  1051.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressU
  1052.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressV
  1053.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP); // addressW
  1054.  
  1055.     const CD3DX12_STATIC_SAMPLER_DESC anisotropicWrap(
  1056.         4, // shaderRegister
  1057.         D3D12_FILTER_ANISOTROPIC, // filter
  1058.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressU
  1059.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressV
  1060.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressW
  1061.         0.0f,                             // mipLODBias
  1062.         8);                               // maxAnisotropy
  1063.  
  1064.     const CD3DX12_STATIC_SAMPLER_DESC anisotropicClamp(
  1065.         5, // shaderRegister
  1066.         D3D12_FILTER_ANISOTROPIC, // filter
  1067.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressU
  1068.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressV
  1069.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressW
  1070.         0.0f,                              // mipLODBias
  1071.         8);                                // maxAnisotropy
  1072.  
  1073.     return { 
  1074.         pointWrap, pointClamp,
  1075.         linearWrap, linearClamp, 
  1076.         anisotropicWrap, anisotropicClamp };
  1077. }
  1078.  
  1079. float BlendApp::GetHillsHeight(float x, float z)const
  1080. {
  1081.     return 0.3f*(z*sinf(0.1f*x) + x*cosf(0.1f*z));
  1082. }
  1083.  
  1084. XMFLOAT3 BlendApp::GetHillsNormal(float x, float z)const
  1085. {
  1086.     // n = (-df/dx, 1, -df/dz)
  1087.     XMFLOAT3 n(
  1088.         -0.03f*z*cosf(0.1f*x) - 0.3f*cosf(0.1f*z),
  1089.         1.0f,
  1090.         -0.3f*sinf(0.1f*x) + 0.03f*x*sinf(0.1f*z));
  1091.  
  1092.     XMVECTOR unitNormal = XMVector3Normalize(XMLoadFloat3(&n));
  1093.     XMStoreFloat3(&n, unitNormal);
  1094.  
  1095.     return n;
  1096. }
  1097.